package eg.ci.mvn.service.core.config.swagger;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.spring.SpringUtil;
import eg.ci.mvn.service.core.config.git.GitRepositoryState;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.*;

@Slf4j
@Configuration
public class SwaggerV3Config {

    /** summary comparator 按 Operation 注解的summary值进行排序 */
    private Comparator<Map.Entry<String, PathItem>> summaryComparator =
            Comparator.comparing(a -> Optional.ofNullable(a.getValue().readOperations().get(0).getSummary()).orElse(""));


    /**
     * 根据@Tag 上的排序，写入x-order
     *
     * @return the global open api customizer
     */
    @Bean
    public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() {
        return openApi -> {
            if (openApi.getTags() != null) {
//                openApi.getTags().forEach(tag -> {
//                    Map<String, Object> map = new HashMap<>();
//                    map.put("x-order", RandomUtil.randomInt(0, 100));
//                    tag.setExtensions(map);
//                });
            }
            if (openApi.getPaths() != null) {
                Paths paths = new Paths();
                openApi.getPaths().entrySet().stream().sorted(summaryComparator)
                        .forEachOrdered(e -> paths.put(e.getKey(), e.getValue()));
                openApi.setPaths(paths);

            }

        };
    }

    @Bean
    public OpenAPI customOpenAPI() {
        String custVersionName = SpringUtil.getBean(GitRepositoryState.class).getCustVersionName();
        return new OpenAPI()
                .info(new Info()
                        .title("接口规范")
                        .description("接口开发文档")
                        .termsOfService("http://group.xxx.cn")
                        .version(custVersionName)
                        .contact(new Contact().name("技术开发组").email("").url(""))//作者
                        .license(new License().name("MIT").url("")));
    }

}
